package com.qk.manangement.controller;

import com.github.pagehelper.PageInfo;
import com.qk.common.response.PageResult;
import com.qk.common.response.Result;
import com.qk.entity.pojo.Dept;
import com.qk.entity.request.dept.AddDeptRequest;
import com.qk.entity.request.dept.UpdateDeptRequest;
import com.qk.manangement.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;

    /**
     * 添加部门
     *
     * @param addDeptRequest 部门信息
     * @return 添加结果
     */
    @PostMapping
    public Result addDept(@RequestBody @Validated AddDeptRequest addDeptRequest) {

        boolean success = deptService.addDept(addDeptRequest);
        if (!success) {
            return Result.error("添加部门失败");
        }
        return Result.success();

    }

    /**
     * 分页查询
     */
    @GetMapping
    public Result list(String name, Integer status,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Dept> pageInfo = deptService.getDeptList(name, status, page, pageSize);
        PageResult<Dept> deptPageResult = new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
        return Result.success(deptPageResult);
    }


    /**
     * 删除部门
     *
     * @param id 部门id
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean success = deptService.deleteDept(id);
        if (!success) {
            return Result.error("删除部门失败");
        }
        return Result.success();
    }

    /**
     * 根据id查询部门
     *
     * @param id 部门id
     *           返回部门信息
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    /**
     * 修改部门信息
     * @param updateDeptRequest 部门信息
     * @return 修改结果
     */
    @PutMapping
    public Result update(@Validated @RequestBody UpdateDeptRequest updateDeptRequest) {
        boolean success = deptService.updateDept(updateDeptRequest);
        if (!success) {
            return Result.error("修改部门失败");
        }
        return Result.success();
    }

    /**
     *  获取部门列表
     * @return
     */
    @GetMapping("/list")
    public Result list() {
        return Result.success(deptService.list());
    }
}




